<template>
  <div
    class="svvg"
    ref="svvg"
    @mousewheel="zooming"
    :style="{
      transform: `translate(${translateX}px,${translateY}px) scale(${zoom})`,
    }"
  >
    <svg width="500" height="500">
      <rect
      x="200"
      y="200"
        width="100"
        height="100"
        style="fill: rgb(0, 0, 255); stroke-width: 1; stroke: rgb(0, 0, 0)"
      />
    </svg>
  </div>
</template>

<script>
export default {
  data() {
    return {
      zoom: 1,
      mouseX: null,
      mouseY: null,
      offsetX: null,
      offsetY: null,
      translateX: 0,
      translateY: 0,
    };
  },
  watch: {
    //   translateX: function (newVal,oldVal) {
    //      oldVal+this.scale *(this.mouseX/this.oldVal);
    //   },

  },
  methods: {
    zooming(e) {
      let event = e || window.event;
      console.log(1);
      event.preventDefault(); // 阻止默认滚动行为

      const zoomIntensity = 0.1; // 缩放增量
      const delta = Math.sign(event.deltaY); // 获取滚动方向

      // 设置鼠标位置
      this.mouseX = event.clientX;
      this.mouseY = event.clientY;

      // 计算新的缩放比例
      const newZoom = this.zoom + delta * zoomIntensity;

      let svvgDom = this.$refs.svvg;
      // 计算缩放前鼠标在容器中的位置
      const containerX = this.mouseX-this.translateX;
      const containerY = this.mouseY - this.translateY;

      // 计算缩放之后鼠标在容器中的位置
      const scaledContainerX = containerX * (newZoom / this.zoom);
      const scaledContainerY = containerY * (newZoom / this.zoom);

      // 计算容器位置需要调整的偏移量
      this.offsetX = containerX - scaledContainerX;
      this.offsetY = containerY - scaledContainerY;

      this.zoom = newZoom;

      this.$refs.svvg.style.transformOrigin = `${containerX}px ${containerY}px`;

      // 应用缩放和偏移样式
      this.$refs.svvg.style.transform = `scale(${this.zoom}) translate(${this.offsetX}px, ${this.offsetY}px)`;
    },
  },
};
</script>

<style>
.svvg {
  width: 500px;
  height: 500px;
  background: green;
}
</style>